package com.zhihui.online.utils;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 阿里支付工具类
 */
@Component
public class PayTemplate {

    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    //签名方式
    private static final String SIGN_TYPE = "RSA2";


    @Autowired
    private PayConfig payConfig;



    /**
     * 获取支付表单
     * @param orderId
     * @return
     * @throws Exception
     */
    public String pay(String orderId, Integer price) throws Exception {

        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(payConfig.getGatewayUrl(), payConfig.getAppId(),
                payConfig.getAppPrivateKey(), FORMAT, CHARSET, payConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
        request.setNotifyUrl(payConfig.getNotifyUrl() + "/alipay/notify");
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no",orderId);  // 我们自己生成的订单编号
        bizContent.put("total_amount", price); // 订单的总金额，
        String name = "阿良TV永久会员";
        bizContent.put("subject", name);   // 支付的名称
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置
        bizContent.put("qr_pay_mode", "2");  // 表单格式
        bizContent.put("qrcode_width", "200");  // 二维码宽度
        request.setBizContent(bizContent.toString());
        request.setReturnUrl("http://localhost:8080/front/orders"); // 支付完成后自动跳转到本地页面的路径
        // 执行请求，拿到响应的结果，返回给浏览器
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            throw new Exception();
        }
        return form;
    }
}
